<template>
    <el-dialog :model-value="props.addEditCategoryDialog" :title="title === 'add' ? '添加分类' : '修改分类'" :before-close="closeDialog">
      <el-form ref="ruleFormRef" :model="form" label-width="auto" :rules="formRules.rules">
        <el-form-item label="分类名称" prop="cat_name">
           <el-input v-model="form.cat_name"/>
        </el-form-item>

        <el-form-item label="父级分类" v-if="title === 'add'">
           <el-cascader clearable placeholder="---请选择---" v-model="jilianValue" :options="options" :props="{label: 'cat_name', value: 'cat_id', children: 'children'}" @focus="handleChange"/>
        </el-form-item>
      </el-form>
  
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeDialog">取消</el-button>
          <el-button type="primary" @click="onSubmit(ruleFormRef)">确定</el-button>
        </div>
      </template>
    </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref, watch } from 'vue'
import type { FormInstance } from 'element-plus'
import { GetCascaderFnc, AddCategoryFnc, EditCategoryFnc } from '@/api/category'

const props = defineProps({
   addEditCategoryDialog: {type: Boolean, required: true},
   typeFlag: {type: String, required: true},
   pageNow: {type: Number, required: true},
   pageSize: {type: Number, required: true},
   catName: {type: String, required: true},
   catID: {type: Number, required: true}
})
const emit = defineEmits(['showDialog', 'init'])

const title = ref('')
const ruleFormRef = ref<FormInstance>()
const objForm = ref({}) // 复制对象  用做修改对象时做比较 是否有做修改  
const jilianValue = ref([]) // 级联选中的值
const options = ref([]) // 级联所有的数据

// 表单数据
const form = reactive({ cat_name: '' })

// 表单验证规则
const formRules = reactive({
  rules: {
    cat_name: [
      {required: true, message: '请输入分类名称', trigger: 'blur'},
      {min: 1, max: 5, message: '长度在3-5个字符', trigger: 'blur'}
    ]
  }
})

// 获取级联数据
const handleChange = async () => {
  const res = await GetCascaderFnc({type: 2})
  if(res.data.meta.status === 200) {
    options.value = res.data.data
  }
}

watch([() => props.typeFlag, () => props.catName], ([newType, newCatName]) => {
   title.value = newType
   form.cat_name = newCatName
   objForm.value = {...form}
})

// 关闭dialog
const closeDialog = () => {
  emit('showDialog', false, title.value) 
  form.cat_name = ''
}

// 公共消息
const publicMsg = (msg: string) => {
  ElMessage({type: 'success', message: msg, duration: 1000, onClose: () => {
    emit('showDialog', false, title.value)
    emit('init', props.pageNow, props.pageSize) 
    form.cat_name = ''
    jilianValue.value = []
  }})
}

// 提交表单
const onSubmit = async (formEl: FormInstance | undefined) => {
  if(!formEl) return  
  await formEl.validate(async (valid) => {
    if(valid) {
       if(title.value === 'add') { // 添加分类
        const res = await AddCategoryFnc({cat_name: form.cat_name, cat_pid: 0, cat_level: 0})
        if(res.data.meta.status === 201) {
            publicMsg(res.data.meta.msg)
        }
       } else { // 修改分类
         if(JSON.stringify(objForm.value) === JSON.stringify(form)) { // 未做修改
          emit('showDialog', false, 'edit')
          return
         } else { // 修改了
            if(JSON.stringify(objForm.value) === JSON.stringify(form)) { // 未做修改
              emit('showDialog', false, 'edit')
              return
            } else { // 修改了
              const res =  await EditCategoryFnc(props.catID, form)
              if(res.data.meta.status === 200) {
                publicMsg(res.data.meta.msg)
              }
            }
         }
       }
    }
  })
}
</script>